<template>
  <div class=''>

    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">

      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon />

      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center class="mt-15">
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品内容" />
        <el-step title="完成" />
      </el-steps>

      <!-- 表单区域 -->
      <el-form
        :model="addGoodFrom" :rules="addGoodFromRules" ref="addGoodFromRef"
        label-width="100px" label-position="top" class="mt-15"
      >
        <!-- tabs 区域 -->
        <el-tabs
          tab-position="left" v-model="activeIndex"
          :before-leave="beforeTabLeave" @tab-click="tabClick"
        >
          <!-- 基本信息 -->
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称:" prop="goods_name">
              <el-input v-model="addGoodFrom.goods_name" />
            </el-form-item>

            <el-form-item label="商品价格:" prop="goods_price">
              <el-input v-model.number="addGoodFrom.goods_price" type="number" />
            </el-form-item>

            <el-form-item label="商品重量:" prop="goods_weight">
              <el-input v-model.number="addGoodFrom.goods_weight" type="number" />
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addGoodFrom.goods_number" type="number" />
            </el-form-item>

            <!-- 选择商品分类的级联选择框 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodFrom.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                :show-all-levels="false"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数 -->
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
            v-for="(item, i) in manyAttrList" :key="i"
            :label="item.attr_name"
            >
              <!-- 复选框 -->
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                  v-for="(cb, j) in item.attr_vals" :key="j"
                  :label="cb" border
                  >
                  </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性 -->
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
            v-for="(item, i) in onlyAttrList" :key="i"
            :label="item.attr_name"
            >
              <!-- 输入框 -->
              <el-input v-model="item.attr_vals" />
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片 -->
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :action="uploadURL"
              :headers="headerObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容 -->
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor
            v-model="addGoodFrom.goods_introduce"
            ></quill-editor>
            <!-- 添加按钮 -->
            <el-button
            type="primary" class="mt-15"
            @click="addGood"
            >添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>

    <!-- 预览图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
      >

      <!-- 内容主体区域 -->
      <img :src="PreviewPath" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'Add',
  props: {

  },
  data () {
    return {
      activeIndex: '0',
      // 与表单数据相关
      addGoodFrom: {
        goods_name: '',
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        goods_cat: [],
        // 图片数组
        pics: [],
        goods_introduce: '',
        // 参数数组
        attrs: []
      },
      addGoodFromRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 与联级有关表单
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 参数列表
      manyAttrList: [],
      // 属性列表
      onlyAttrList: [],
      // 图片上传路径
      uploadURL: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      // 图片上传请求头参数
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览路径
      PreviewPath: '',
      previewDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    cateId () {
      const catList = this.addGoodFrom.goods_cat
      if (catList.length === 3) {
        return catList[catList.length - 1]
      } else {
        return null
      }
    }
  },
  methods: {
    // 获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.cateList = res.data
    },

    // 获取参数列表
    async getArrtList (id, sel) {
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`, {
          params: {
            sel
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      if (sel === 'many') {
        // 将 字符串 转化为数组
        res.data.forEach(v => {
          v.attr_vals = v.attr_vals ? v.attr_vals.split(' ') : []
          v.inputVisible = false
          v.inputValue = ''
        })
        this.manyAttrList = res.data
      } else {
        this.onlyAttrList = res.data
      }
    },

    // 监视 tab 切换
    beforeTabLeave (NewActiveName, OldActiveName) {
      if (OldActiveName === '0' && this.addGoodFrom.goods_cat.length !== 3) {
        this.$message.error('您还没有填完数据')
        return false
      }

      return true
    },
    // tab 切换 触发事件
    tabClick () {
      if (this.activeIndex === '1') {
        this.getArrtList(this.cateId, 'many')
      } else if (this.activeIndex === '2') {
        this.getArrtList(this.cateId, 'only')
      }
    },
    // 监听图片被点击事件
    handlePreview (file) {
      this.PreviewPath = file.response.data.url
      this.previewDialogVisible = true
    },

    // 图片移除
    handleRemove (file) {
      // 获取临时路径
      const filePath = file.response.data.tmp_path
      // 从表单数据中获取该路劲 的索引值
      const i = this.addGoodFrom.pics.findIndex(v =>
        v.pic === filePath
      )
      // 根据索引值删除数据
      this.addGoodFrom.pics.splice(i, 1)
    },
    // 图片上传成功
    handleSuccess (response, file, fileList) {
      // 拼接图像信息对象
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodFrom.pics.push(picInfo)
    },

    // 执行添加商品
    addGood () {
      this.$refs.addGoodFromRef.validate(async vaild => {
        if (!vaild) {
          return this.$message.error('请填写完必要的信息')
        }
        // 执行添加商品的业务逻辑
        // 深拷贝的表单数据
        const fromDeep = _.cloneDeep(this.addGoodFrom)
        fromDeep.goods_cat = fromDeep.goods_cat.join(',')
        // 处理动态参数
        this.manyAttrList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodFrom.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyAttrList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodFrom.attrs.push(newInfo)
        })
        fromDeep.attrs = this.addGoodFrom.attrs
        // 发起添加商品的网络请求
        const { data: res } = await this.$http.post('goods', fromDeep)
        if (res.meta.status !== 201) return this.$message.error('商品添加失败')
        this.$message.success('商品添加成功')

        // 跳转回商品列表页面
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom: 15px;
  font-size: 12px;
}
.box-card{
  box-shadow:  0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.mt-15{
  margin-top: 15px;
}
.goods-lable{
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding-right: 16px;
}
.el-checkbox{
  margin: 0 5px 0 0 !important;
}
.previewImg{
  width: 100%;
}

</style>
